package nancal.mp.service.jenkins.publish

import nancal.mp.service.jenkins.JenkinsPublishJob
import nbcp.base.extend.AsString

//fun JenkinsJob.f1_init_ops_var(): FunctionContent {
//
//    /**
//     * 有的服务器执行下面语句会报错：
//     * git_commit_time=＄(git log --pretty=format:'%cd' ＄git_commit_id -1  --date=format:'%Y%m%d.%H%M%S')
//     */
//    return FunctionContent(
//        "init-ops-var", """
//cd code
//    docker_image_version=＄(date "+%Y%m%d.%H%M%S")
//    git_commit_id=＄(git rev-parse HEAD)
//    git_commit_time=＄(git log --pretty=format:"%ci" ＄git_commit_id -1)
//    git_commit_time=＄(echo ＄git_commit_time | cut -d ' ' -f 1,2 | sed 's|-||g' | sed 's|:||g' | sed 's| |.|g')
//cd -
//
//echo  ＄docker_image_version  > .ops.docker_image_version.txt
//echo  ＄git_commit_id  > .ops.git_commit_id.txt
//echo  ＄git_commit_time  > .ops.git_commit_time.txt
//
//echo -e "\n"`date "+%Y-%m-%d %H:%M:%S"` "生成系统文件: .ops.git_commit_id.txt, .ops.git_commit_time.txt, Dockerfile, code/.ops.build.sh"
//"""
//    )
//}

fun JenkinsPublishJob.f1_load_ops_var(): FunctionContent {
    return FunctionContent(
            "load-ops-var", """
source ${buildStartShell}  && start-job
"""
    )
}

fun JenkinsPublishJob.f1_show_file(): FunctionContent {
    return FunctionContent(
            "show-file", """
r=＄?
file_name="＄1"
line="＄2"
line_tail="＄3"
if [ "＄file_name" == "" ]; then
    echo "没有 file_name 参数"
    return ＄r || 1
fi

if [ ! -f ＄file_name ]; then
    echo "找不到文件 ＄file_name"
    return ＄r || 1
fi

if [[ ＄debug == true ]]; then
    cat ＄file_name;
    return ＄r
fi

if [ "＄line_tail" == "" ]; then
    line_tail=＄line
fi

total=`cat ＄file_name | wc -l`
show_total=＄(( ＄line + ＄line_tail ))
if [ ＄show_total -ge ＄total ]; then
    cat ＄file_name
else
    echo "前＄line行日志:"
    head -n ＄line ＄file_name
    echo "〘…后＄line_tail行日志:…〙" 
    tail -n ＄line_tail ＄file_name
fi
return ＄r
"""
    )
}

//fun JenkinsPublishJob.f1_print_report(): FunctionContent {
//    var kv = this.task.buildInfo::class.java.AllFields
//            .filter {
//                it.name.IsIn(
//                        "dockerImage",
//                        "dockerImageName",
//                        "dockerImageVersion",
//                        "gitCommitId",
//                        "gitCommitAt",
//                        "buildNumber",
//                        "targetEnv"
//                ) == false
//            }
//
//
//    var list2 = kv
//            .map {
//                return@map CnAnnotationUtil.getCnValue(it).AsString(it.name) + ": " + it.get(this.task.buildInfo).AsString()
//            }
//            .sorted()
//            .groupBy { it.endsWith("名") || it.endsWith("名称") }
//
//
//    var list = mutableListOf<String>();
//    list.add("产品线: ${this.task.productLine.name} (${this.task.productLine.code})")
//    list.addAll(list2.get(true) ?: listOf())
//
//    list.add("开发语言: ${this.task.language}:${this.task.languageVersion}")
//    if (this.task.currentGitFolder.config.docker.id.HasValue) {
//        list.add("自定义docker: ${this.task.currentGitFolder.config.docker.name}")
//    }
//
//    if (this.task.currentGitFolder.config.k8sDeployment.id.HasValue) {
//        list.add("自定义K8sDeployment: ${this.task.currentGitFolder.config.k8sDeployment.name}")
//    }
//
//    list.addAll(list2.get(false) ?: listOf())
//
//    return FunctionContent(
//            "print-report", """﹍﹎﹍﹎﹍﹎﹎﹎
//${list.joinToString(const.line_break)}
//部署环境: ${this.task.buildInfo.targetEnv.AsString { mor.dev.appDeploySetting.getAppDeploySetting().code }}
//是否单模块: ${is_root_path()}
//docker镜像版本: ＄docker_image_version
//git仓库: ${this.task.gitData?.url.AsString()}
//git提交id: ＄git_commit_id
//git提交时间: ＄git_commit_time
//生成时间: ${LocalDateTime.now().AsString()}
//﹊﹉﹊﹉﹊﹉﹊﹊""".split("\n")
//            .filter { it.HasValue }
//            .map { "\techo \"${it.trim()}\"" }
//            .joinToString("\n")
//    )
//}

//fun JenkinsJob.f1_install_skywalking_agent(): FunctionContent {
//    return FunctionContent(
//        "install-skywalking-agent", """
//echo "下载 skywalking agent 组件并解压"
//echo "wget http://172.16.250.2:30000/skywalking/get/agent.zip"
//wget  ${if (slice) "-q" else ""} http://172.16.250.2:30000/skywalking/get/agent.zip -O agent.zip
//unzip -o  -d ./code  agent.zip  &>/dev/null
//"""
//    )
//}

//
//fun JenkinsJob.f1_mvn_switch_pom(): FunctionContent {
//    if (this.appDeploySetting.pipelineTemplate == PipelineTemplateEnum.Native) {
//        return FunctionContent.empty("mvn-switch-pom")
//    }
//
//    return FunctionContent(
//        "mvn-switch-pom", """
//folder="＄1"
//ms_deploy_env="＄2"
//
//if [ "＄ms_deploy_env" == "" ]; then
//    return
//fi
//
//echo "wget -q --header=\"Content-type:text/plain\" --post-data=\"\＄(cat code/＄folder/pom.xml)\" ${appDeploySetting.mpIntegrationApiHost}/ops/cmd/mvn-switch-pom?msDeployEnv=＄ms_deploy_env -O .ms.pom.xml"
//wget ${if (slice) "-q" else ""} --header="Content-type:text/plain" --post-data="＄(cat code/＄folder/pom.xml)" ${appDeploySetting.mpIntegrationApiHost}/ops/cmd/mvn-switch-pom?msDeployEnv=＄ms_deploy_env -O .ms.pom.xml
//
//line_count=＄(awk 'END{print NR}' .ms.pom.xml)
//if [ ＄line_count -gt 1 ]; then
//    echo "使用服务器 mvn-switch-pom 处理过的 pom.xml!"
//    echo "mv -f .ms.pom.xml code/＄folder/pom.xml"
//    mv -f .ms.pom.xml code/＄folder/pom.xml
//else
//    echo "不处理 pom.xml!"
//fi
//"""
//    )
//}


fun JenkinsPublishJob.f1_ms_deploy_env_yml(): FunctionContent {
    return FunctionContent(
            "ms-deploy-env-yml", """
folder="＄1"
${this.appDeploySetting.sudo} chmod a+rw code -R

echo "mkdir -p res/yml && mkdir -p res/lib && mkdir -p code/＄folder/lib-runtime "
mkdir -p res/yml && mkdir -p res/lib && mkdir -p code/＄folder/lib-runtime


resources=＄(find code/＄folder -type d -name resources | grep -v test | sort | head -1)

if [ "＄resources" != "" ]; then
    fc=＄(ls res/yml/ -l|grep "^-"| wc -l)
    if [ ＄fc -gt 0 ]; then
        echo "mv -n res/yml/*  ＄resources/"
        mv -n res/yml/* ＄resources/
    fi
else 
    echo "找不到 code/＄folder 文件夹下的 resources!"
fi

fc=＄(ls res/lib/ -l|grep "^-"| wc -l)

if [ ＄fc -gt 0 ]; then 
    echo "mv -n res/lib/*  code/＄folder/lib-runtime/"
    mv -n res/lib/*  code/＄folder/lib-runtime/
fi

if [ -f "res/web-server.zip" ]; then 
    echo "unzip -q -o res/web-server.zip -d code/＄folder/web-server"
    unzip -q -o res/web-server.zip -d code/＄folder/web-server
fi


if [ -f "res/res.zip" ]; then 
    echo "unzip -q -o res/res.zip -d code/＄folder/res-runtime"
    unzip -q -o res/res.zip -d code/＄folder/res-runtime
fi
"""
    )
}


fun JenkinsPublishJob.f1_ops_git_clone(): FunctionContent {
    return FunctionContent(
            "ops-git-clone", """
url="＄1"
branch="＄2"
if [ "＄url" == "" ]; then
    url="${this.task.gitData?.url.AsString()}"
fi
if [ "＄branch" == "" ]; then
    branch="${this.task.buildInfo.gitBranch}"
fi

git clone --depth=1  --single-branch -b ＄branch ＄url code

"""
    )
}